package com.microboot.service;

import com.alibaba.fastjson2.JSON;
import com.microboot.entity.product.dto.ProductReqsVO;
import com.microboot.entity.product.dto.ProductRespVO;
import com.microboot.interceptor.ClientLoginInterceptor;
import io.micrometer.common.util.StringUtils;
import lombok.extern.slf4j.Slf4j;
import org.apache.cxf.endpoint.Client;
import org.apache.cxf.jaxws.endpoint.dynamic.JaxWsDynamicClientFactory;
import org.springframework.stereotype.Service;

@Slf4j
@Service
public class ProductService {

    public ProductRespVO getProductInfo(ProductReqsVO productReqsVO) {

        //WebService服务地址
        String address = "http://localhost:8080/services/AutoProductService?wsdl";
        JaxWsDynamicClientFactory dcf = JaxWsDynamicClientFactory.newInstance();
        Client client = dcf.createClient(address);
        client.getOutInterceptors().add(new ClientLoginInterceptor("longxian","root123"));//设置认证账户信息
        String message = "getProductInfo =>> 测试调用数据是否成功";
        Object[] result = null;
        try {
            if(null == productReqsVO){
                productReqsVO = new ProductReqsVO();
            }
            String productName = productReqsVO.getProductName();
            if(StringUtils.isBlank(productName)){
                productReqsVO.setProductName("随机标题："+ Math.random());
            }
            productReqsVO.setProductId(System.currentTimeMillis());
            result = client.invoke("getProductInfo", productReqsVO);
        } catch (Exception e) {
            throw new RuntimeException(e);
        }
        log.info("调用 ProductService ==>> getProductInfo 服务接口返回数据信息为：{}", JSON.toJSONString(result));

        ProductRespVO productRespVO = null;
        if(null != result && result.length > 0){
            if(result[0] instanceof ProductRespVO){
                productRespVO = (ProductRespVO) result[0];
            }else {
                log.error("调用 ProductService ==>> getProductInfo 服务接口响应对象类型不匹配，对象：{}", result[0]);
            }
        }

        return productRespVO;
    }

}
